<template>
  <div
    v-loading="loading"
    element-loading-text="加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.3)"
    class="income-chart"
    :style="{ height: chartHeight + 'px' }"
  >
    <div ref="echart" style="height: 100%;" />
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  name: 'IncomeChart',
  props: {
    chartHeight: {
      type: [String, Number],
      default: '210'
    },
    chartDate: {
      type: Array,
      default: () => []
    },
    chartType: {
      type: String,
      default: 'line' // 默认折线图，可选：line, bar, pie 等
    }
  },
  data() {
    return {
      chart: null,
      resizeObserver: null,
      loading: true,
      seriesData: [], // 修正变量名，更符合语义
      legendData: [] // 修正变量名，更符合语义
    }
  },
  watch: {
    chartDate: {
      handler(newVal) {
        if (!newVal || newVal.length === 0) {
          this.clearChart()
          return
        }
        this.processChartData(newVal)
        this.initChart()
        this.loading = false
      },
      deep: true,
      immediate: true
    },
    chartType: {
      handler(newVal) {
        if (this.chart) {
          this.updateChartType(newVal)
        }
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.observeContainerResize()
    })
  },
  beforeDestroy() {
    this.cleanup()
  },
  methods: {
    // 处理图表数据
    processChartData(chartDate) {
      try {
        this.seriesData = chartDate.map(e => {
          if (!e.list || e.list.length === 0) {
            console.warn('图表数据格式异常:', e)
            return null
          }

          const item = e.list[0]
          return {
            name: item.name,
            type: this.chartType, // 添加 type 属性
            data: Array.isArray(item.value) ? [...item.value] : [],
            smooth: true // 平滑曲线
          }
        }).filter(item => item !== null) // 过滤空数据

        this.legendData = this.seriesData.map(item => item.name)
      } catch (error) {
        console.error('处理图表数据失败:', error)
        this.seriesData = []
        this.legendData = []
      }
    },

    // 初始化图表
    initChart() {
      try {
        const chartDom = this.$refs.echart
        if (!chartDom) {
          console.warn('图表容器未找到')
          return
        }

        // 如果图表已存在，先销毁
        if (this.chart) {
          this.chart.dispose()
        }

        this.chart = echarts.init(chartDom)

        const option = this.getChartOption()
        this.chart.setOption(option)

        // 添加图表事件
        this.bindChartEvents()
      } catch (error) {
        console.error('初始化图表失败:', error)
      }
    },

    // 获取图表配置
    getChartOption() {
      const xAxisData = this.chartDate[0]?.time || []

      return {
        tooltip: {
          trigger: 'axis',
          backgroundColor: 'rgba(0, 0, 0, 0.8)',
          borderColor: '#777',
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          data: this.legendData,
          textStyle: {
            color: '#fff'
          },
          top: 'top',
          type: 'scroll' // 图例过多时可滚动
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '15%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: this.chartType === 'line', // 折线图两边留白
          data: xAxisData,
          axisLabel: {
            color: '#9692ac',
            rotate: xAxisData.length > 6 ? 45 : 0 // 数据多时旋转标签
          },
          axisLine: {
            lineStyle: {
              color: '#534d77'
            }
          },
          axisTick: {
            alignWithLabel: true
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            color: '#d1cfdb',
            formatter: this.getYAxisFormatter()
          },
          splitLine: {
            lineStyle: {
              color: 'rgba(83, 77, 119, 0.5)',
              type: 'dashed'
            }
          }
        },
        series: this.seriesData,
        animation: true, // 开启动画
        animationDuration: 1000 // 动画时长
      }
    },

    // 更新图表类型
    updateChartType(newType) {
      if (!this.chart) return

      try {
        const option = this.chart.getOption()
        option.series.forEach(series => {
          series.type = newType
        })

        // 根据图表类型调整边界留白
        option.xAxis[0].boundaryGap = newType === 'line'

        this.chart.setOption(option)
      } catch (error) {
        console.error('更新图表类型失败:', error)
      }
    },

    // 获取Y轴格式化器
    getYAxisFormatter() {
      // 根据数据类型返回合适的格式化器
      return (value) => {
        if (value >= 10000) {
          return (value / 10000).toFixed(1) + '万'
        } else if (value >= 1000) {
          return (value / 1000).toFixed(1) + '千'
        }
        return value
      }
    },

    // 绑定图表事件
    bindChartEvents() {
      if (!this.chart) return

      this.chart.on('click', (params) => {
        this.$emit('chart-click', params)
      })

      this.chart.on('legendselectchanged', (params) => {
        this.$emit('legend-change', params)
      })
    },

    // 监听容器尺寸变化
    observeContainerResize() {
      if (typeof ResizeObserver === 'undefined') {
        console.warn('ResizeObserver not supported, using window resize')
        window.addEventListener('resize', this.handleResize)
        return
      }

      this.resizeObserver = new ResizeObserver((entries) => {
        clearTimeout(this.resizeTimer)
        this.resizeTimer = setTimeout(() => {
          this.resizeChart()
        }, 200)
      })

      if (this.$el) {
        this.resizeObserver.observe(this.$el)
      }
    },

    // 处理窗口大小变化
    handleResize() {
      clearTimeout(this.resizeTimer)
      this.resizeTimer = setTimeout(() => {
        this.resizeChart()
      }, 200)
    },

    // 调整图表大小
    resizeChart() {
      if (this.chart) {
        try {
          this.chart.resize()
        } catch (error) {
          console.warn('调整图表大小失败:', error)
        }
      }
    },

    // 清空图表
    clearChart() {
      if (this.chart) {
        this.chart.clear()
      }
      this.seriesData = []
      this.legendData = []
    },

    // 清理资源
    cleanup() {
      // 移除事件监听
      window.removeEventListener('resize', this.handleResize)

      // 断开观察者
      if (this.resizeObserver) {
        this.resizeObserver.disconnect()
        this.resizeObserver = null
      }

      // 清理定时器
      clearTimeout(this.resizeTimer)

      // 销毁图表
      if (this.chart) {
        this.chart.dispose()
        this.chart = null
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.income-chart {
  margin-top: 18px;
  width: 100%;
  background: rgba(44, 37, 89, 1);
  padding: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
</style>
